//
//  AppDelegate.m
//  WorkGo
//
//  Created by 李树志 on 2017/9/30.
//  Copyright © 2017年 李树志. All rights reserved.
//

#import "AppDelegate.h"
#import "WGCoreDataManager.h"
#import "WGDay.h"
#import "WGDataService.h"

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    NSString *dateString = [formatter stringFromDate:date];
    
    NSManagedObjectContext *context = [WGCoreDataManager sharedManager].managedObjectContext;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"WGDay" inManagedObjectContext:context];
    fetchRequest.entity = entity;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"date == %@", dateString];
    fetchRequest.predicate = predicate;
    NSError *error = nil;
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    if (error) {
        NSLog(@"Core Data Fetch Error: %@", error);
    }
    if (fetchedObjects.count > 0) {
        // 已存在本地数据,暂不更新
        NSLog(@"已存在本地数据,暂不更新");
    } else {
        // 本地数据不存在,立即更新数据
        NSLog(@"本地数据不存在,立即更新数据");
        [[WGDataService sharedService] refreshDataProgress:^(float progress) {
            NSLog(@"%3.2f",progress);
        } completion:^(NSError *error) {
            NSLog(@"数据更新完成");
        }];
    }
    
    return YES;
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    [[WGCoreDataManager sharedManager] saveContext];
}

@end
